package mysql

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"shop-api/pkg/log"
)

func WithClient(hand func(db *gorm.DB) error) error {
	dsn := fmt.Sprintf(
		"%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("mysql.user"),
		viper.GetString("mysql.password"),
		viper.GetString("mysql.host"),
		viper.GetString("mysql.port"),
		viper.GetString("mysql.dbname"),
	)

	fmt.Println(dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return err
	}

	defer func() {
		dd, err := db.DB()
		if err != nil {
			log.LogError(err)
		}
		err = dd.Close()
		if err != nil {
			log.LogError(err)
		}
	}()
	return hand(db)
}
